const express = require('express');
const { body, param, validationResult } = require('express-validator');
const { authMiddleware, adminMiddleware } = require('../middlewares/auth.middleware');
const categoryController = require('../controllers/category.controller');
const router = express.Router();

// 获取所有分类 (公开接口)
router.get('/', categoryController.getAllCategories);

// 获取分类详情 (公开接口)
router.get('/:id', [
  param('id').isMongoId().withMessage('无效的分类ID')
], async (req, res, next) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }
  next();
}, categoryController.getCategoryById);

// --- 以下是管理员接口 ---

// 创建分类 (管理员)
router.post('/', [
  authMiddleware,
  adminMiddleware,
  body('name').trim().isLength({ min: 2, max: 20 }).withMessage('分类名称长度必须在2-20个字符之间'),
  body('key').trim().isLength({ min: 2, max: 30 }).withMessage('键名长度必须在2-30个字符之间')
    .matches(/^[a-z0-9-]+$/).withMessage('键名只能包含小写字母、数字和连字符'),
  body('description').trim().isLength({ min: 1, max: 200 }).withMessage('描述长度必须在1-200个字符之间'),
  body('tags').optional().isArray().withMessage('标签必须是数组'),
  body('order').optional().isInt({ min: 1, max: 100 }).withMessage('排序值必须在1-100之间')
], async (req, res, next) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }
  next();
}, categoryController.createCategory);

// 更新分类 (管理员)
router.put('/:id', [
  authMiddleware,
  adminMiddleware,
  param('id').isMongoId().withMessage('无效的分类ID'),
  body('name').optional().trim().isLength({ min: 2, max: 20 }).withMessage('分类名称长度必须在2-20个字符之间'),
  body('description').optional().trim().isLength({ min: 1, max: 200 }).withMessage('描述长度必须在1-200个字符之间'),
  body('tags').optional().isArray().withMessage('标签必须是数组'),
  body('order').optional().isInt({ min: 1, max: 100 }).withMessage('排序值必须在1-100之间')
], async (req, res, next) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }
  next();
}, categoryController.updateCategory);

// 删除分类 (管理员)
router.delete('/:id', [
  authMiddleware,
  adminMiddleware,
  param('id').isMongoId().withMessage('无效的分类ID')
], async (req, res, next) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }
  next();
}, categoryController.deleteCategory);

// 批量更新分类排序 (管理员)
router.put('/batch/order', [
  authMiddleware,
  adminMiddleware,
  body('orders').isArray().withMessage('orders必须是数组'),
  body('orders.*.id').isMongoId().withMessage('无效的分类ID'),
  body('orders.*.order').isInt({ min: 1, max: 100 }).withMessage('排序值必须在1-100之间')
], async (req, res, next) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }
  next();
}, categoryController.updateCategoriesOrder);

module.exports = router;